package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /***
     * 发送验证码
     * @param phone
     * @param
     */
    @PostMapping("/sendMsg")
    public void sendMsg(@RequestBody User user){
        String phone = user.getPhone();
        //1.随机生成一个验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        //2.存入session中
        //session.setAttribute("code",code);
        //2.存入redis缓存中
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        log.info("短信验证码是:{}",code);
        //3.发送短信
        //SMSUtils.sendMessage("阿里云短信测试","SMS_154950909","18221024878",code);
    }


    /****
     * 用户登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        String phone = (String) map.get("phone");
        String code = (String) map.get("code");
        //1.获取session中的code
        //String sessionCode = (String) session.getAttribute("code");
        String redisCode = (String) redisTemplate.opsForValue().get(phone);
        //2.判断用户名是否存在
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>();
        lqw.eq(User::getPhone,phone);

        //3.判断验证码是否正确
        if(redisCode != null && redisCode.equals(code)){
            User user = userService.getOne(lqw);
            if(user == null){
                //创建用户
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //标志
            redisTemplate.delete(phone);
            session.setAttribute("user",user.getId());
            return R.success(user);
        }
        redisTemplate.delete(phone);
        return  R.error("验证码不正确");
    }


    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session){
        session.invalidate();
        return R.success("退出成功");
    }
}
